package com.qiwx.pigeon.fragment.manager;

import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.qiwx.pigeon.R;
import com.qiwx.pigeon.Utils.DBSqlUtil;
import com.qiwx.pigeon.Utils.MyToast;
import com.qiwx.pigeon.activity.manager.CageManagerActivity;
import com.qiwx.pigeon.adapter.manager.CageAdapter;
import com.qiwx.pigeon.base.BaseFragment;
import com.qiwx.pigeon.base.BaseMVPFragment;
import com.qiwx.pigeon.data.CageStatusConfig;
import com.qiwx.pigeon.data.db.CageModel;
import com.qiwx.pigeon.data.params.CageParam;
import com.qiwx.pigeon.data.vo.CageBean;
import com.qiwx.pigeon.data.vo.CageBeanVo;
import com.qiwx.pigeon.data.vo.pageinfo.PageInfo;
import com.qiwx.pigeon.presenter.CagePresenter;
import com.qiwx.pigeon.viewinterface.ICageView;
import com.qiwx.pigeon.widget.ArrowView;
import com.qiwx.pigeon.widget.itemderection.LineItemDecoration;

import org.litepal.LitePal;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @description
 * @Author qiwx
 * @Date 2020-03-26 10:49
 **/
public class CagemanagerFragment extends BaseMVPFragment<ICageView, CagePresenter> implements ICageView {
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.lin_nodata)
    LinearLayout linNodata;
    @BindView(R.id.rel_content)
    RelativeLayout rel_content;
    @BindView(R.id.btn_select)
    Button btnSelect;
    @BindView(R.id.arrow_left)
    ArrowView arrowLeft;
    @BindView(R.id.txt_prepage)
    TextView txtPrepage;
    @BindView(R.id.txt_nextpage)
    TextView txtNextpage;
    @BindView(R.id.arrow_right)
    ArrowView arrowRight;
    @BindView(R.id.btn_save)
    Button btnSave;
    int wh_id;//仓库Id
    List<CageBeanVo> data = new ArrayList<>();
    CageAdapter adapter;
    CageParam cageParam = new CageParam();

    int pageNo = 1;//页码
    int pageAll;//总页码
    int pageSize = 10;//每页显示10条记录
    int allNums = 0;//总共有多少条记录
    boolean isSelect = false;//是否全选
    List<CageModel> dbDatas;//数据库内容
    boolean isCL;//是否是存栏
    int status_start = 0;
    int status_end = CageStatusConfig.STATUS_PD;
    public int status;
    CageManagerActivity mActivity;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_cage_manager_layout;
    }


    @Override
    public void initAfterOnCreate() {
        super.initAfterOnCreate();
        //查询一共有多少条记录
        // queryCount();
        cageParam.setPageSize(pageSize);
        cageParam.setPageNum(pageNo);
        if (getActivity() != null && getActivity() instanceof CageManagerActivity) {
            mActivity = ((CageManagerActivity) getActivity());
        } else {
            return;
        }

        initView();
        initEvent();
        loadData();

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            onRefresh();
        }
    }

    @Override
    public CagePresenter createPresenter() {
        return new CagePresenter(new WeakReference<>(this));

    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Bundle bundle = this.getArguments();//得到从Activity传来的数据
        if (bundle != null) {
            wh_id = bundle.getInt("wh_id", 0);
            status = bundle.getInt("status", 0);
            if (status == 1) {//0是存栏 1是空笼
                status_start = CageStatusConfig.STATUS_YGYM;
                status_end = CageStatusConfig.STATUS_SG;
                isCL = true;
            } else {
                status_start = CageStatusConfig.STATUS_KL;
                status_end = CageStatusConfig.STATUS_KL;
                isCL = false;
            }
            cageParam.setStatus(status);
            cageParam.setWh_id(wh_id);
            cageParam.setStatusStart(status_start);
            cageParam.setStatusEnd(status_end);
        }
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    // 查询有多少条记录
    public void queryCount() {
//        allNums = LitePal.where("wh_id=? and status>=? and status<=?", wh_id + "", status_start, status_end).count(CageModel.class);
//        pageAll = allNums / pageSize;
//        if (allNums % pageSize != 0) {
//            pageAll += 1;
//        }
//        txtNextpage.setText(pageAll + "");
    }

    private void initView() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        recyclerview.setLayoutManager(linearLayoutManager);
        recyclerview.addItemDecoration(new LineItemDecoration(2));
        adapter = new CageAdapter(R.layout.adapter_cage_item, data);
        recyclerview.setAdapter(adapter);
        arrowLeft.changeArrowLeft();
        arrowRight.changeArrowRight();

    }

    private void initEvent() {
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                boolean isCheck = data.get(position).isSelected();
                data.get(position).setSelected(!isCheck);
                adapter.notifyDataSetChanged();
            }
        });
    }

    public void loadData() {
//        List<wh_id> result = LitePal.where("wh_id=?and status=?", wh_id, status).find(wh_id.class);
//        cageParam.setPageNum(1);
//        mPresenter.queryCagesByPage(cageParam);

        goPage(1);
    }

    public int getCount() {
        return data.size();
    }

    public void setData(PageInfo<CageBeanVo> bean) {
        allNums = bean.getTotal();
        pageAll = allNums / pageSize;
        if (allNums % pageSize != 0) {
            pageAll += 1;
        }
        pageNo = bean.getPageNum();
        txtPrepage.setText(pageNo + "");
        txtNextpage.setText(pageAll + "");
        data.clear();
        data.addAll(bean.getList());
        if (data.size() > 0) {
            linNodata.setVisibility(View.GONE);
            rel_content.setVisibility(View.VISIBLE);
        } else {
            linNodata.setVisibility(View.VISIBLE);
            rel_content.setVisibility(View.GONE);
        }
//        if (getActivity() != null && getActivity() instanceof CageManagerActivity) {
//            ((CageManagerActivity) getActivity()).updateCount();
//        }
        adapter.notifyDataSetChanged();

    }

    private void goPage(int index) {

//        int offset = 0;
//        if (index <= pageAll) {
//            offset = (index - 1) * pageSize;
//        }
        cageParam.setPageNum(index);
        cageParam.setStatus(status);
        if (isCL) {//0是存栏 1是空笼
            status_start = CageStatusConfig.STATUS_YGYM;
            status_end = CageStatusConfig.STATUS_PD;
        } else {
            status_start = CageStatusConfig.STATUS_KL;
            status_end = CageStatusConfig.STATUS_KL;
        }
        cageParam.setStatusStart(status_start);
        cageParam.setStatusEnd(status_end);
        cageParam.setWh_id(wh_id);
        mPresenter.queryCagesByPage(cageParam);
//
//        dbDatas = LitePal.limit(pageSize).offset(offset).where("wh_id=? and status>=? and status<=?", wh_id, status_start, status_end).find(CageModel.class);
//        data.clear();
//        if (dbDatas != null && dbDatas.size() > 0) {
//            for (int i = 0; i < dbDatas.size(); i++) {
//                CageBean cageBean = new CageBean();
//                cageBean.setNumber(dbDatas.get(i).getNumber());
//                cageBean.setStatus(dbDatas.get(i).getStatus());
//                cageBean.setId(dbDatas.get(i).getId());
//                data.add(cageBean);
//            }
//            adapter.notifyDataSetChanged();
//        }
//        if (data.size() > 0) {
//            linNodata.setVisibility(View.GONE);
//            rel_content.setVisibility(View.VISIBLE);
//        } else {
//            linNodata.setVisibility(View.VISIBLE);
//            rel_content.setVisibility(View.GONE);
//        }
//        if (getActivity() != null && getActivity() instanceof CageManagerActivity) {
//            ((CageManagerActivity) getActivity()).updateCount();
//        }
    }

    public void onRefresh() {
        if (pageNo > 1) {
            goPage(pageNo - 1);
        } else {
            goPage(pageNo);
        }
    }

    private void selectAll(boolean isSelect) {
        for (int i = 0; i < data.size(); i++) {
            data.get(i).setSelected(isSelect);
        }
        adapter.notifyDataSetChanged();

    }

    private void saveData() {
        List<Integer> ids = new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
            if (data.get(i).isSelected()) {
                //CageModel cm = dbDatas.get(i);
                ids.add(data.get(i).getId());
//                if (isCL) { //存栏页面 设置成空笼 空笼页面设置成存栏
//                    DBSqlUtil.setCageKL(cm, true);
//                } else {
//                    DBSqlUtil.setCageCL(cm, true);
//                }
            }
        }
        CageParam cageParam = new CageParam();
        cageParam.setWh_id(wh_id);
        cageParam.setIds(ids);
        cageParam.setStatus(status);
//        if (isCL) { //存栏页面 将当前状态传过去 后台来写逻辑
//            cageParam.setStatus(CageStatusConfig.STATUS_YGYM);
//            //DBSqlUtil.setCageKL(cm, true);
//        } else {
//            cageParam.setStatus(CageStatusConfig.STATUS_KL);
//
//            // DBSqlUtil.setCageCL(cm, true);
//        }

        updateBtnSelectShow();
        mPresenter.updateCageStatus(cageParam);
        // queryCount();

        MyToast.showLong("操作成功");

    }

    private void updateBtnSelectShow() {
        isSelect = !isSelect;
        if (isSelect) {
            btnSelect.setText("取消选择");
        } else {
            btnSelect.setText("全选");
        }
    }

    public void addCage(int amount) {
        CageParam cageParam = new CageParam();
        cageParam.setAddCageAmount(amount);
        cageParam.setWh_id(wh_id);
        mPresenter.addCage(cageParam);
    }


    @OnClick({R.id.btn_select, R.id.arrow_left, R.id.arrow_right, R.id.btn_save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_select:
                updateBtnSelectShow();
                selectAll(isSelect);
                break;
            case R.id.arrow_left:
                if (pageNo == 1) {
                    MyToast.showShort("已经是第一页");
                } else {
                    pageNo = pageNo - 1;
                    goPage(pageNo);
                    txtPrepage.setText(pageNo + "");

                }
                break;
            case R.id.arrow_right:
                if (pageNo == pageAll) {
                    MyToast.showShort("已经是最后一页");
                } else {
                    pageNo = pageNo + 1;
                    goPage(pageNo);
                    txtPrepage.setText(pageNo + "");

                }

                break;
            case R.id.btn_save:
                saveData();
                break;
        }
    }


    @Override
    public void onAddCageSuccess(Integer bean) {
        MyToast.showLong("添加成功");
        if (isCL) {
            goPage(1);
        }

    }

    @Override
    public void onQueryCageSuccess(PageInfo<CageBeanVo> bean) {
        if (bean != null
                && bean.getList() != null
        ) {
            mActivity.setAmount(isCL ? 1 : 0, bean.getTotal());
            setData(bean);
        }
    }

    @Override
    public void onUpdateCageSuccess(int c_id) {
        goPage(pageNo);
        ((CagemanagerFragment)mActivity.fragmentList.get(isCL?1:0)).onRefresh();


    }

    @Override
    public void onFailure(String error) {

    }

//    public String getTitle() {
//        return  status.equals("1")?"存栏":"空笼";
//    }
//        return "存栏" + "(" + getCount() + ")";
//    }
}
